//
//  HSQKeyboardView.m
//  LiTianDecoration
//
//  Created by administrator on 2018/7/24.
//  Copyright © 2018年 administrator. All rights reserved.
//

static float bottomHeight = 230.0f; //底部视图高度
static float viewMargin = 8.0f; //按钮距离上边距
static float viewHeight = 36.0f; //按钮视图高度

#import "HSQKeyboardView.h"
#import "HSQKeyBoardTextView.h"
#import "HSQEmotionKeyboard.h"  // 表情键盘
#import "HSQMoreView.h"  // 相机和相册键盘
#import "HWEmotion.h"

@interface HSQKeyboardView ()<UITextViewDelegate,HSQMoreViewDelegate>

@property (nonatomic, strong) UIView *backView;

@property (nonatomic, strong) UIButton *emojiBtn;

@property (nonatomic, strong) UIButton *moreBtn;

@property (nonatomic, strong) HSQKeyBoardTextView *textView;

@property (nonatomic, strong) HSQEmotionKeyboard *emojiView;

@property (nonatomic, strong) HSQMoreView *moreView;

@property (nonatomic, assign) CGFloat totalYOffset;

@property (nonatomic, assign) float keyboardHeight; //键盘高度

@property (nonatomic, assign) double keyboardTime; //键盘动画时长

@property (nonatomic, assign) BOOL emojiClick; //点击表情按钮

@property (nonatomic, assign) BOOL moreClick; //点击更多按钮

@property (nonatomic, assign) BOOL isShowKeyBoard; // 键盘是否显示

@end

@implementation HSQKeyboardView

- (id)initWithFrame:(CGRect)frame {
    
    if (self = [super initWithFrame:frame]) {
        
        self.backgroundColor = [UIColor colorWithRed:0.96 green:0.96 blue:0.96 alpha:1.00];
                
        //监听键盘出现、消失
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
        
        // 表情选中的通知
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(emotionDidSelect:) name:HWEmotionDidSelectNotification object:nil];
        
        // 删除文字的通知
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(emotionDidDelete) name:HWEmotionDidDeleteNotification object:nil];
        
        //创建视图
        [self creatView];
        
        // 添加底部控制视图
        [self AddBottomView];
    }
    return self;
}

/**
 * @brief 创建视图
 */
- (void)creatView {
    
    self.backView.frame = CGRectMake(0, 0, self.width, self.height);
    
    //表情按钮
    self.emojiBtn.frame = CGRectMake(viewMargin, viewMargin, viewHeight, viewHeight);
    
    //输入视图
    self.textView.frame = CGRectMake(CGRectGetMaxX(self.emojiBtn.frame) + viewMargin, viewMargin, KScreenWidth - (CGRectGetMaxX(self.emojiBtn.frame) + viewMargin) * 2, viewHeight);
    
    //加号按钮
    self.moreBtn.frame = CGRectMake(CGRectGetMaxX(self.textView.frame) + viewMargin, self.height - viewMargin - viewHeight, viewHeight, viewHeight);
}

/**
 * @brief 添加底部控制视图
 */
- (void)AddBottomView{
    
    // 更多视图
    HSQMoreView *moreView = [[HSQMoreView alloc] init];
    moreView.frame = CGRectMake(0, KScreenHeight, KScreenWidth, (bottomHeight + KSafeBottomHeight));
    moreView.delegate = self;
    [self addSubview:moreView];
    self.moreView = moreView;
    
    // 表情键盘
    HSQEmotionKeyboard *emojiView = [[HSQEmotionKeyboard alloc] init];
    emojiView.frame = CGRectMake(0, KScreenHeight, KScreenWidth, (bottomHeight + KSafeBottomHeight));
    [self addSubview:emojiView];
    self.emojiView = emojiView;
}

/**
 *  表情被选中了
 */
- (void)emotionDidSelect:(NSNotification *)notification{
    
    HWEmotion *emotion = notification.userInfo[HWSelectEmotionKey];
    
    [self.textView insertEmotion:emotion];
}

/**
 *  @brief 删除文字
 */
- (void)emotionDidDelete{
    
    [self.textView deleteBackward];
}

#pragma mark ====== init ======
- (UIView *)backView {
    
    if (!_backView) {
        
        _backView = [UIView new];
        
        _backView.layer.borderWidth = 1;
        
        _backView.layer.borderColor = [UIColor colorWithRed:0.88 green:0.88 blue:0.89 alpha:1.00].CGColor;
        
        [self addSubview:_backView];
    }
    return _backView;
}

//表情按钮
- (UIButton *)emojiBtn {
    
    if (!_emojiBtn) {
        
        _emojiBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        
        [_emojiBtn setBackgroundImage:[UIImage imageNamed:@"emojiImg"] forState:UIControlStateNormal];
        
        [_emojiBtn addTarget:self action:@selector(emojiBtn:) forControlEvents:UIControlEventTouchUpInside];
        
        [self.backView addSubview:_emojiBtn];
    }
    return _emojiBtn;
}

//更多按钮
- (UIButton *)moreBtn {
    
    if (!_moreBtn) {
        
        _moreBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        
        [_moreBtn setBackgroundImage:[UIImage imageNamed:@"moreImg"] forState:UIControlStateNormal];
        
        [_moreBtn addTarget:self action:@selector(moreBtn:) forControlEvents:UIControlEventTouchUpInside];
        
        [self.backView addSubview:_moreBtn];
    }
    return _moreBtn;
}

- (HSQKeyBoardTextView *)textView {
    
    if (!_textView) {
        
        _textView = [[HSQKeyBoardTextView alloc] init];
        
        _textView.font = [UIFont systemFontOfSize:16];
        
        [_textView textValueDidChanged:^(CGFloat textHeight) {
            
            [self changeFrame:textHeight];
            
        }];
        _textView.maxNumberOfLines = 5;
        
        _textView.layer.cornerRadius = 4;
        
        _textView.layer.borderWidth = 1;
        
        _textView.layer.borderColor = [UIColor colorWithRed:0.88 green:0.88 blue:0.89 alpha:1.00].CGColor;
        
        _textView.delegate = self;
        
        _textView.returnKeyType = UIReturnKeySend;
        
        [self.backView addSubview:_textView];
    }
    return _textView;
}

#pragma mark ====== 改变输入框大小 ======
- (void)changeFrame:(CGFloat)height {
    
    CGRect frame = self.textView.frame;
    
    frame.size.height = height;
    
    self.textView.frame = frame; //改变输入框的frame
    
    //当输入框大小改变时，改变backView的frame
    self.backView.frame = CGRectMake(0, 0, KScreenWidth, height + (viewMargin * 2));
    
    self.frame = CGRectMake(0, KScreenHeight - KSafeTopeHeight - self.backView.height - _keyboardHeight, KScreenWidth, self.backView.height + (bottomHeight + KSafeBottomHeight));
    
    self.emojiView.frame = CGRectMake(0, self.backView.height, KScreenWidth, (bottomHeight + KSafeBottomHeight));
        
    //改变更多按钮、表情按钮的位置
    self.emojiBtn.frame = CGRectMake(viewMargin, self.backView.height - viewHeight - viewMargin, viewHeight, viewHeight);
    
    self.moreBtn.frame = CGRectMake((self.textView.mj_x + self.textView.mj_w)+ viewMargin, self.backView.height - viewHeight - viewMargin, viewHeight, viewHeight);
    
    //主要是为了改变VC的tableView的frame
    [self changeTableViewFrame];
}

#pragma mark ====== 改变tableView的frame ======
- (void)changeTableViewFrame {
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(keyboardChangeFrameWithMinY:)]) {
        
        [self.delegate keyboardChangeFrameWithMinY:self.mj_y];
    }
}

#pragma mark ====== 键盘将要出现 ======
- (void)keyboardWillShow:(NSNotification *)notification {
    
    self.isShowKeyBoard = YES;
    
    NSDictionary *userInfo = notification.userInfo;
    
    CGRect endFrame = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    //获取键盘的高度
    self.keyboardHeight = endFrame.size.height;
    
    //键盘的动画时长
    CGFloat duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    [UIView animateWithDuration:duration delay:0 options:[notification.userInfo[UIKeyboardAnimationCurveUserInfoKey] integerValue] animations:^{
        
        self.frame = CGRectMake(0, endFrame.origin.y - self.backView.height - KSafeTopeHeight, KScreenWidth, self.height);
        
        self.emojiView.mj_y = (bottomHeight + KSafeBottomHeight);
        
        self.moreView.mj_y = (bottomHeight + KSafeBottomHeight);
        
        HSQLog(@"==self.frame==%@",NSStringFromCGRect(self.frame));
        
        [self changeTableViewFrame];
        
    } completion:nil];
}

#pragma mark ====== 键盘将要消失 ======
- (void)keyboardWillHide:(NSNotification *)notification {
    
    self.keyboardHeight = (bottomHeight + KSafeBottomHeight);
    
    //如果是弹出了底部视图时
    if (self.moreClick || self.emojiClick) {
        
        return;
    }
    
    [UIView animateWithDuration:0.25 animations:^{
        
        self.frame = CGRectMake(0, KScreenHeight - KSafeTopeHeight - self.backView.height, KScreenWidth, self.backView.height);
        
        [self changeTableViewFrame];
    }];
}

#pragma mark ====== 点击发送按钮 ======
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    
    //判断输入的字是否是回车，即按下return
    if ([text isEqualToString:@"\n"]){
        
        if (self.delegate && [self.delegate respondsToSelector:@selector(textViewContentText:)]) {
            
            [self.delegate textViewContentText:textView.text];
        }
        
        [self changeFrame:viewHeight];
        
        textView.text = @"";
        
        /*这里返回NO，就代表return键值失效，即页面上按下return，
         不会出现换行，如果为yes，则输入页面会换行*/
        return NO;
    }
    return YES;
}

#pragma mark ====== 表情按钮 ======
- (void)emojiBtn:(UIButton *)btn {
    
    self.isShowKeyBoard = YES;
    
    self.moreClick = NO;
    
    if (self.emojiClick == NO) {
        
        self.emojiClick = YES;
        
        //回收键盘
        [self.textView resignFirstResponder];
        
        [UIView animateWithDuration:0.25 animations:^{
            
            self.frame = CGRectMake(0, KScreenHeight - KSafeTopeHeight - self.backView.height - (bottomHeight + KSafeBottomHeight), KScreenWidth, self.backView.height + (bottomHeight + KSafeBottomHeight));
            
            self.moreView.frame = CGRectMake(0, KScreenHeight, KScreenWidth, (bottomHeight + KSafeBottomHeight));
            
            // 显示表情键盘
            self.emojiView.frame = CGRectMake(0, self.backView.height, KScreenWidth, (bottomHeight + KSafeBottomHeight));
                        
            [self changeTableViewFrame];
        }];
        
    }
    else
    {
        [self.textView becomeFirstResponder];
    }
}

#pragma mark ====== 加号按钮 ======
- (void)moreBtn:(UIButton *)btn {
    
    self.isShowKeyBoard = YES;
    
    self.emojiClick = NO; //主要是设置表情按钮为未点击状态
    
    if (self.moreClick == NO) {
        
        self.moreClick = YES;
        
        //回收键盘
        [self.textView resignFirstResponder];
        
        //改变更多、self的frame
        [UIView animateWithDuration:0.25 animations:^{
            
            self.frame = CGRectMake(0, KScreenHeight - KSafeTopeHeight - self.backView.height - (bottomHeight + KSafeBottomHeight), KScreenWidth, self.backView.height + (bottomHeight + KSafeBottomHeight));
            
            self.emojiView.frame = CGRectMake(0, KScreenHeight, KScreenWidth, (bottomHeight + KSafeBottomHeight));
            
            self.moreView.frame = CGRectMake(0, self.backView.height, KScreenWidth, (bottomHeight + KSafeBottomHeight));
            
            HSQLog(@"===self.moreView.frame==%@",NSStringFromCGRect(self.moreView.frame));
            
            [self changeTableViewFrame];
        }];
    }
    else  //再次点击更多按钮
    {
        //键盘弹起
        [self.textView becomeFirstResponder];
    }
}

/**
 * @brief 输入框将要被点击
 */
- (void)textViewDidBeginEditing:(UITextView *)textView{
    
    self.emojiClick = NO;
    
    self.moreClick = NO;
    
    HSQLog(@"===11111");
}

/**
 * @brief 输入框将要收回
 */
- (void)textViewDidEndEditing:(UITextView *)textView{

    
    HSQLog(@"===2222222222");
}

/**
 * @brief 选择系统的相册
 */
- (void)KeyBoardPhotoAlbumBtnClickAction:(UIButton *)sender{
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(SelectTheSystemPhotoAlbumBtnClickAction:)]) {
        
        [self.delegate SelectTheSystemPhotoAlbumBtnClickAction:sender];
    }
}

/**
 * @brief 选择系统的相机
 */
- (void)KeyBoardCameraBtnClickAction:(UIButton *)sender{
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(SelectTheSystemCameraBtnClickAction:)]) {
        
        [self.delegate SelectTheSystemCameraBtnClickAction:sender];
    }
}

/**
 * @brief 监听输入框的变化
 */
- (void)textViewDidChange:(UITextView *)textView{
    
    if (textView.text.length == 0)
    {
        self.emojiView.Send_Button.enabled = NO;
    }
    else
    {
        self.emojiView.Send_Button.enabled = YES;
    }
}

/**
 * @brief 取消键盘界面
 */
- (void)CancelSystemKeyBoardView{
    
    if (self.isShowKeyBoard == YES)
    {
        [UIView animateWithDuration:0.25 animations:^{
            
            self.isShowKeyBoard = NO;
            
            [self.textView resignFirstResponder];
            
            self.frame = CGRectMake(0, KScreenHeight - KSafeTopeHeight - self.backView.height - KSafeBottomHeight, KScreenWidth, self.backView.height);
            
            self.moreView.frame = CGRectMake(0, KScreenHeight, KScreenWidth, (bottomHeight + KSafeBottomHeight));
            
            self.emojiView.frame = CGRectMake(0, KScreenHeight, KScreenWidth, (bottomHeight + KSafeBottomHeight));
            
            [self changeTableViewFrame];
        }];
    }
}

#pragma mark ====== 移除监听 ======
- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}



@end
